#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/2/4 12:06
# @Author  : Ramsey
# @Site    : zh
# @File    : response.py
# @Software: PyCharm
import json
from parsel import Selector
from urllib.parse import urljoin as _urljoin
from spider_framework.http.request import Request


class Response:
    def __init__(self, url: str, *, request: Request, body: bytes = b"", headers: dict = None, status: int = 200):
        self.url = url
        self.request = request
        self.body = body
        self.headers = headers or {}
        self.status = status
        self.encoding = request.encoding
        self._cache = None
        self._selector = None

    @property
    def text(self):
        if self._cache:
            return self._cache

        try:
            self._cache = self.body.decode(self.encoding)
        except UnicodeDecodeError:
            raise Exception(f"编码错误: {self.encoding}")
        else:
            return self._cache

    def json(self):
        return json.loads(self.text)

    def urljoin(self, url):
        return _urljoin(self.url, url)

    def xpath(self, xpath_string):
        if self._selector is None:
            self._selector = Selector(self.text)
        return self._selector.xpath(xpath_string)

    @property
    def meta(self):
        return self.request.meta

    def __str__(self):
        return f"<Response {self.url} {self.status}>"


if __name__ == "__main__":
    pass
